package com.marchsoft.campushelp.security.service;

import com.marchsoft.campushelp.domain.CampusUserTable;
import com.marchsoft.campushelp.security.vo.MyJwtUser;
import com.marchsoft.campushelp.service.CampusUserTableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 源
 * Date: 2020-03-14
 * Time: 10:42
 */
@Service("securityUserService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class SecurityUserService implements UserDetailsService {
    @Autowired
    CampusUserTableService campusUserTableService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        CampusUserTable user = campusUserTableService.findUserByPhone(s);
        System.out.println(user.getPhone()+"---------"+s);
        if(user==null) {
            //抛出错误，用户不存在
            throw new UsernameNotFoundException("手机号 "+s+"不存在");
        }

        return createMyJwtUser(user);
    }
    public UserDetails createMyJwtUser(CampusUserTable user){
        //获取用户权限
        List<String> aa = new ArrayList<>();
        aa.add(user.getPermission());
        List<GrantedAuthority> simpleGrantedAuthorityStream = aa.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return new MyJwtUser(
                user.getId(),
                user.getNickName(),
                user.getAvatar(),
                user.getVipTyp(),
                user.getLoginPassword(),
                user.getPayPassword(),
                user.getName(),
                user.getAge(),
                user.getPhone(),
                user.getCampus(),
                user.getUserType(),
                user.getDisable(),
                user.getDeleteType(),
                user.getCreatTime(),
                user.getPermission(),
                simpleGrantedAuthorityStream
                );

    }
}
